package com.life.notes.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.life.notes.dao.SysUserRoleMapper;
import com.life.notes.dto.UserRoleQueryPara;
import com.life.notes.model.SysUserRoleEntity;
import com.life.notes.service.SysUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description 用户与角色业务实现
 * @Author Sans
 * @CreateTime 2019/9/14 15:57
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRoleEntity> implements SysUserRoleService {

    @Override
    public IPage<SysUserRoleEntity> listPage(UserRoleQueryPara filter) {
        Page<SysUserRoleEntity> page = new Page<>(filter.getPage(),filter.getLimit());
        return this.baseMapper.selectUserRoles(page, filter);
    }

    @Override
    public List<SysUserRoleEntity> list(UserRoleQueryPara filter) {
        return this.baseMapper.selectUserRoles(filter);
    }

    @Override
    public Integer saveUserRole(SysUserRoleEntity para) {
        if (para.getId()!=null) {
            this.baseMapper.updateById(para);
        } else {
            this.baseMapper.insert(para);
        }
        return para.getId();
    }

    @Override
    public void saveUserRole(UserRoleQueryPara para) {
        Integer roleId = para.getRoleId();
        String userIds = para.getUserIds();
        this.baseMapper.deleteByRoleId( roleId );
        if( StringUtils.isNotBlank( userIds ) ){
            String[] userIdArrays = userIds.split( "," );
            if( userIdArrays.length > 0 ){
                for (String userId : userIdArrays) {
                    SysUserRoleEntity userRole = new SysUserRoleEntity();
                    userRole.setRoleId( roleId );
                    userRole.setUserId( Integer.parseInt( userId ) );
                    this.baseMapper.insert( userRole );
                }
            }
        }
    }
}